package cn.dao;

import cn.entity.User;
import cn.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User login(String username, String password) {
        Connection con = DBUtil.getCon();
        PreparedStatement pst = null;
        ResultSet rs = null;
        User user = null;
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?;";

        try {
            pst = con.prepareStatement(sql);
            // 设置查询参数
            pst.setString(1, username);
            pst.setString(2, password);

            // 执行查询
            rs = pst.executeQuery();

            // 检查结果集是否有数据
            if (rs.next()) {
                // 创建 User 对象
                user = new User(username, password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            DBUtil.closeCon(con);
        }
        return user;
    }

    @Override
    public boolean register(String username, String password) {
        boolean flag = true;

        Connection con = DBUtil.getCon();
        PreparedStatement pst = null;
        String sql = "insert into user(username,password) values(?,?)";
        try {
            pst = con.prepareStatement(sql);
            pst.setString(1, username);
            pst.setString(2, password);
            pst.executeUpdate();
        } catch (SQLException e) {
            flag = false;
            throw new RuntimeException(e);
        } finally {
            DBUtil.closeCon(con);
        }
        return flag;
    }
}
